package com.ocom.payhandle.controller;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.constant.PayHandleUrl;
import com.ocom.common.entity.card.EntityXfRecordProcess;
import com.ocom.common.entity.card.EntityXfRecordProcessExxx;
import com.ocom.common.request.payhandle.QrCardPayRequest;
import com.ocom.common.request.payhandle.QrCodeRefundRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.DateUtils;
import com.ocom.common.utils.RandomUtil;
import com.ocom.common.utils.ResultUtil;
import com.ocom.payhandle.fun.PayFunService;
import com.ocom.payhandle.mq.business.saveorder.SaveOrderProductService;
import com.ocom.payhandle.service.*;
import com.ocom.payhandle.vo.MqSaveOrderVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.List;


@Slf4j
@RestController
public class TimerController {


    @Autowired
    private XfRecordProcessService xfRecordProcessService;

    @Autowired
    private XfRecordProcessExxxService xfRecordProcessExxxService;

    @Autowired
    private XfGoodsListProcessService xfGoodsListProcessService;

    @Autowired
    private SaveOrderProductService saveOrderProductService;

    @Autowired
    private XfMerchPayInfoService xfMerchPayInfoService;

    @Autowired
    private XfRecordProcessExtendService xfRecordProcessExtendService;

    @Autowired
    PayFunService payFunService;




    //定时任务 代扣订单
    @GetMapping(PayHandleUrl.URL_delayPay)
    public Result delayPay() {

        handlePay(100l);
        handlePay(600l);
        return ResultUtil.success();
    }


    //定时任务 代扣订单
    @GetMapping(PayHandleUrl.URL_cancelDelayPay)
    public Result cancelDelayPay() {

        handleCancelDelayPay(100l);
        handleCancelDelayPay(600l);
        return ResultUtil.success();
    }

    private void handlePay(long companyId) {
        List<EntityXfRecordProcess> list = xfRecordProcessService.getDelayPayList(companyId, -11, 205);
//        System.out.println(list);
        if (list == null || list.size() == 0) return;

        for (EntityXfRecordProcess entityXfRecordProcess : list) {

            try {
                //更新成支付中
                entityXfRecordProcess.setPayState(0);
                xfRecordProcessService.updateById(entityXfRecordProcess);

                QrCardPayRequest qrCardPayRequest = new QrCardPayRequest();
                qrCardPayRequest.setCompanyId(entityXfRecordProcess.getComId());
                qrCardPayRequest.setMachNo(entityXfRecordProcess.getDeviceNo());
                qrCardPayRequest.setTradeNo(entityXfRecordProcess.getOrderNo());
                qrCardPayRequest.setAmount(entityXfRecordProcess.getRealMoney().intValue());
                qrCardPayRequest.setConsType(entityXfRecordProcess.getConsType());
                qrCardPayRequest.setConsState(entityXfRecordProcess.getConsState());
                qrCardPayRequest.setType(1);
                JSONObject jsonObject = new JSONObject();
                int payState = payFunService.withholding(entityXfRecordProcess, qrCardPayRequest, null, jsonObject, 3);
                log.info("厦门订餐发起支付 【{}】 【{}】 【{}】", entityXfRecordProcess.getOrderNo(), payState, jsonObject);

                if (payState == 2) {
                    try {
                        MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                        mqSaveOrderVo.setComId(entityXfRecordProcess.getComId());
                        mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                        mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                        mqSaveOrderVo.setType(3);
                        saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));

                        xfGoodsListProcessService.xfGoodsListRrfund(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrderNo());
                    } catch (Exception e) {
                        StackTraceElement ste = e.getStackTrace()[0];
                        log.info("请求方式xm02:【{}】,机器号:【{}】,厦门修改状态为失败-改成功库:【{}】,异常的返回:【{}】,行号:【{}】", "离线处理预支付", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                    }
                }
            } catch (Exception e) {
                log.info("处理厦门订餐支付异常  【{}】【{}】", entityXfRecordProcess.getOrderNo(), e);
            }
        }
    }


    private void handleCancelDelayPay(long companyId) {
        List<EntityXfRecordProcess> list = xfRecordProcessService.cacelDealyPayList(companyId);
        if (list == null || list.size() == 0) return;
        for (EntityXfRecordProcess entityXfRecordProcess : list) {

            try {
                //更新成失败
                xfRecordProcessService.cacelDealyPay(entityXfRecordProcess.getComId(),entityXfRecordProcess.getId());

                xfGoodsListProcessService.xfGoodsListRrfund(entityXfRecordProcess.getComId(), entityXfRecordProcess.getOrderNo());

                try {
                    MqSaveOrderVo mqSaveOrderVo = new MqSaveOrderVo();
                    mqSaveOrderVo.setComId(entityXfRecordProcess.getComId());
                    mqSaveOrderVo.setId(entityXfRecordProcess.getId());
                    mqSaveOrderVo.setMachNo(entityXfRecordProcess.getDeviceNo());
                    mqSaveOrderVo.setType(3);
                    saveOrderProductService.saveOrder(JSON.toJSONString(mqSaveOrderVo));
                } catch (Exception e) {
                    StackTraceElement ste = e.getStackTrace()[0];
                    log.info("请求方式xm02:【{}】,机器号:【{}】,厦门修改状态为失败-改成功库:【{}】,异常的返回:【{}】,行号:【{}】", "离线处理预支付", entityXfRecordProcess.getDeviceNo(), entityXfRecordProcess, e, ste.getLineNumber());
                }

            } catch (Exception e) {
                log.info("处理厦门订餐支付异常  【{}】【{}】", entityXfRecordProcess.getOrderNo(), e);
            }
        }
        return;
    }



    //厦门优惠导致第一笔退款
    @GetMapping(PayHandleUrl.URL_xmDiscountRefund)
    public Result xmDiscountRefund() {

        handleXmDiscountRefund(100l);
        handleXmDiscountRefund(600l);
        return ResultUtil.success();
    }


    private void handleXmDiscountRefund(long companyId) {
        List<EntityXfRecordProcessExxx> xfRecordProcessExxxes = xfRecordProcessExxxService.getRefunding(companyId);
        if(xfRecordProcessExxxes==null || xfRecordProcessExxxes.size()<=0){
            return;
        }

        for (EntityXfRecordProcessExxx entityXfRecordProcessExxx:xfRecordProcessExxxes){

            try {
                QrCodeRefundRequest request = new QrCodeRefundRequest();
                request.setMachNo(entityXfRecordProcessExxx.getDeviceNo());
                request.setCompanyId(entityXfRecordProcessExxx.getComId());
                request.setTradeNo(entityXfRecordProcessExxx.getDeviceNo() + DateUtils.dateTimeNow() + RandomUtil.generateNumber(6));
                request.setOrigTradeNo(entityXfRecordProcessExxx.getOrderNo());
                Integer refundAmount = entityXfRecordProcessExxx.getRealMoney().intValue();
                request.setRefundAmount(Math.abs(refundAmount));

                Result result = payFunService.qrCodeRefund(request);

                if(result.getCode()==200){
                    xfRecordProcessExtendService.updateCancelState(entityXfRecordProcessExxx.getComId(),entityXfRecordProcessExxx.getId(),1000);
                    continue;
                }

                if(entityXfRecordProcessExxx.getCancelState()==2){
                    xfRecordProcessExtendService.updateCancelState(entityXfRecordProcessExxx.getComId(),entityXfRecordProcessExxx.getId(),201);
                }else{
                    xfRecordProcessExtendService.updateCancelState(entityXfRecordProcessExxx.getComId(),entityXfRecordProcessExxx.getId(),entityXfRecordProcessExxx.getCancelState()+1);
                }
            }catch (Exception e){
                log.error("优惠退款处理异常 【{}】【{}】",entityXfRecordProcessExxx,e);
            }


        }

    }


    //定时任务 代扣订单
    @GetMapping(PayHandleUrl.URL_timerTransportOrder)
    public Result timerTransportOrder() {

        String month = DateUtils.getStrDate(new Date(),"yyyyMM");
        String day = DateUtils.getStrDate(new Date(),"dd");

        timerTransportOrderHandle(100l, month,1);
        timerTransportOrderHandle(600l, month,2);

        if(day.equals("01")){
            String befMonth  = DateUtil.format(DateUtil.offsetMonth(new Date(),-1), "yyyyMM");
            timerTransportOrderHandle(100l, befMonth,1);
            timerTransportOrderHandle(600l, befMonth,2);
        }

        return ResultUtil.success();
    }


    void timerTransportOrderHandle(Long comId,String month,Integer part){
        long time1 =System.currentTimeMillis();
        try {
            xfRecordProcessService.timerTransportOrder(comId,month,part);
        }catch (Exception e){
            log.error("定时迁移订单异常 6VOQiGnt 【{}】 ",e);
        }
        try {
            xfRecordProcessService.timerTransportGoodList(comId,month,part);
        }catch (Exception e){
            log.error("定时迁移订单异常 vFue8wfP 【{}】 ",e);
        }
        long time2 =System.currentTimeMillis();
        log.info("定时迁移订单 执行用时  2QAc6f2l 月份【{}】库【{}】用时【{}】 ",month,part,time2-time1);
    }






}
